//
//  CYEmoticon.m
//  LingLingBang
//
//  Created by 郝俊聪 on 15/12/28.
//  Copyright © 2015年 zhaohongling. All rights reserved.
//

#import "CYEmoticon.h"
#import "CYTextAttachment.h"

static NSArray *emoticons;

@implementation CYEmoticon

//定义一个常量记录所有表情

///返回所有的表情对象
+ (NSArray *)allEmoticonsFromPlist
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"emoticons.plist" ofType:nil];
    NSArray *dicArray = [NSArray arrayWithContentsOfFile:path];
    NSMutableArray *tempArray = [NSMutableArray array];
    //字典转模型
    for (NSDictionary *dic in dicArray) {
        //创建对象
        CYEmoticon *emoticon = [[CYEmoticon alloc] init];
        [emoticon setValuesForKeysWithDictionary:dic];
        [tempArray addObject:emoticon];
    }
    //返回补上删除按钮空按钮的表情集合
    return [self emoticonsWith:tempArray];
}

///将带表情符号文字转化为带emoticon图片的属性文字
+ (NSAttributedString *)emoticonStringWith:(NSString *)text lineHeight:(CGFloat)lineHeight
{
    if (!text) {
        return nil;
    }
    //设置匹配方案
    NSString *pattern = @"f[0-9][0-9][0-9]";
    //创建正则表达式
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionDotMatchesLineSeparators error:NULL];
    //开始匹配，并替换文字
    //创建一个可变的属性文本
    NSMutableAttributedString *strM = [[NSMutableAttributedString alloc] initWithString:text];
    //设置字体
    NSArray *results = [regex matchesInString:text options:0 range:NSMakeRange(0,text.length)];
    if (results.count > 0) {
        NSInteger index = results.count - 1;
        while (index >= 0) {
            NSTextCheckingResult *r = results[index--];
            NSRange rang = r.range;
            //取出str
            NSString *emoticonStr = [text substringWithRange:rang];
            if (!emoticons) {
                emoticons = [CYEmoticon allEmoticonsFromPlist];
            }
            //从数组中找出对应的表情对象
            CYEmoticon *emoticon;
            for (CYEmoticon *cyemoticon in emoticons) {
                if ([cyemoticon.str isEqualToString:emoticonStr]) {
                    emoticon = cyemoticon;
                    break;
                }
            }
            if (emoticon) {
                //如果找到了，则替换
                //创建附件
                CYTextAttachment *textAtt = [[CYTextAttachment alloc] init];
                textAtt.str = emoticonStr;
                textAtt.image = [UIImage imageNamed:emoticon.png];
                textAtt.bounds = CGRectMake(0, -4, lineHeight*1.5, lineHeight*1.5);
                //装成属性文本
                NSAttributedString *textAttStr = [NSAttributedString attributedStringWithAttachment:textAtt];
                //替换元文本
                [strM replaceCharactersInRange:rang withAttributedString:textAttStr];
            }
        }
    }
    return strM;
}

//返回设置好字体的富文本
+ (NSAttributedString *)emoticonStringWith:(NSString *)text lineHeight:(CGFloat)lineHeight font:(UIFont *)font textColor:(UIColor *)color
{
    if (!text) {
        return nil;
    }
    //设置匹配方案
    NSString *pattern = @"f[0-9][0-9][0-9]";
    //创建正则表达式
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionDotMatchesLineSeparators error:NULL];
    //开始匹配，并替换文字
    //创建一个可变的属性文本
    NSMutableAttributedString *strM = [[NSMutableAttributedString alloc] initWithString:text];
    //设置字体
    NSArray *results = [regex matchesInString:text options:0 range:NSMakeRange(0,text.length)];
    if (results.count > 0) {
        NSInteger index = results.count - 1;
        while (index >= 0) {
            NSTextCheckingResult *r = results[index--];
            NSRange rang = r.range;
            //取出str
            NSString *emoticonStr = [text substringWithRange:rang];
            if (!emoticons) {
                emoticons = [CYEmoticon allEmoticonsFromPlist];
            }
            //从数组中找出对应的表情对象
            CYEmoticon *emoticon;
            for (CYEmoticon *cyemoticon in emoticons) {
                if ([cyemoticon.str isEqualToString:emoticonStr]) {
                    emoticon = cyemoticon;
                    break;
                }
            }
            if (emoticon) {
                //如果找到了，则替换
                //创建附件
                CYTextAttachment *textAtt = [[CYTextAttachment alloc] init];
                textAtt.str = emoticonStr;
                textAtt.image = [UIImage imageNamed:emoticon.png];
                textAtt.bounds = CGRectMake(0,-4,lineHeight*1.5, lineHeight*1.5);
                //装成属性文本
                NSAttributedString *textAttStr = [NSAttributedString attributedStringWithAttachment:textAtt];
                //替换元文本
                [strM replaceCharactersInRange:rang withAttributedString:textAttStr];
            }
        }
    }
    //设置字体
    [strM addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, strM.length)];
    //设置颜色
    [strM addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, strM.length)];
    return strM;
}

//返回设置好字体的富文本+行间距
+ (NSAttributedString *)emoticonStringWith:(NSString *)text font:(UIFont *)font textColor:(UIColor *)color lineSpacing:(CGFloat)lineSpacing
{
    if (!text) {
        return nil;
    }
    //设置匹配方案
    NSString *pattern = @"f[0-9][0-9][0-9]";
    //创建正则表达式
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionDotMatchesLineSeparators error:NULL];
    //开始匹配，并替换文字
    //创建一个可变的属性文本
    NSMutableAttributedString *strM = [[NSMutableAttributedString alloc] initWithString:text];
    //设置字体
    NSArray *results = [regex matchesInString:text options:0 range:NSMakeRange(0,text.length)];
    if (results.count > 0) {
        NSInteger index = results.count - 1;
        while (index >= 0) {
            NSTextCheckingResult *r = results[index--];
            NSRange rang = r.range;
            //取出str
            NSString *emoticonStr = [text substringWithRange:rang];
            if (!emoticons) {
                emoticons = [CYEmoticon allEmoticonsFromPlist];
            }
            //从数组中找出对应的表情对象
            CYEmoticon *emoticon;
            for (CYEmoticon *cyemoticon in emoticons) {
                if ([cyemoticon.str isEqualToString:emoticonStr]) {
                    emoticon = cyemoticon;
                    break;
                }
            }
            if (emoticon) {
                //如果找到了，则替换
                //创建附件
                CYTextAttachment *textAtt = [[CYTextAttachment alloc] init];
                textAtt.str = emoticonStr;
                textAtt.image = [UIImage imageNamed:emoticon.png];
                textAtt.bounds = CGRectMake(0,-4,font.lineHeight, font.lineHeight);
                //装成属性文本
                NSAttributedString *textAttStr = [NSAttributedString attributedStringWithAttachment:textAtt];
                //替换元文本
                [strM replaceCharactersInRange:rang withAttributedString:textAttStr];
            }
        }
    }
    //设置字体
    [strM addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, strM.length)];
    //设置颜色
    [strM addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, strM.length)];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;// 字体的行间距
    [strM addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, strM.length)];
    return strM;
}

/**
 转化表情富文本+行间距+html文本

 @param text 需要转化的文字
 @param font 字体
 @param color 字体颜色
 @param lineSpacing 行间距
 @return 转化完的富文本
 */
+ (NSAttributedString *)emoticonHtmlStringWith:(NSString *)text font:(UIFont *)font textColor:(UIColor *)color lineSpacing:(CGFloat)lineSpacing
{
    if (!text) {
        return nil;
    }
    //设置匹配方案
    NSString *pattern = @"f[0-9][0-9][0-9]";
    //创建正则表达式
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionDotMatchesLineSeparators error:NULL];
    //开始匹配，并替换文字
    //处理html文本
    NSData *data=[text dataUsingEncoding:NSUnicodeStringEncoding];
    NSDictionary *optoins=@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
                            NSFontAttributeName:font,NSForegroundColorAttributeName:color};
    NSAttributedString *attributeString = [[NSAttributedString alloc] initWithData:data
                                                                         options:optoins
                                                              documentAttributes:nil
                                                                           error:nil];
    NSMutableAttributedString *strM = [[NSMutableAttributedString alloc] initWithAttributedString:attributeString];
    //去掉html标签
    NSString *normalStr = strM.string;
    //遍历
    NSArray *results = [regex matchesInString:normalStr options:0 range:NSMakeRange(0,normalStr.length)];
    if (results.count > 0) {
        NSInteger index = results.count - 1;
        while (index >= 0) {
            NSTextCheckingResult *r = results[index--];
            NSRange rang = r.range;
            //取出str
            NSString *emoticonStr = [normalStr substringWithRange:rang];
            if (!emoticons) {
                emoticons = [CYEmoticon allEmoticonsFromPlist];
            }
            //从数组中找出对应的表情对象
            CYEmoticon *emoticon;
            for (CYEmoticon *cyemoticon in emoticons) {
                if ([cyemoticon.str isEqualToString:emoticonStr]) {
                    emoticon = cyemoticon;
                    break;
                }
            }
            if (emoticon) {
                //如果找到了，则替换
                //创建附件
                CYTextAttachment *textAtt = [[CYTextAttachment alloc] init];
                textAtt.str = emoticonStr;
                textAtt.image = [UIImage imageNamed:emoticon.png];
                textAtt.bounds = CGRectMake(0,-4,font.lineHeight, font.lineHeight);
                //装成属性文本
                NSAttributedString *textAttStr = [NSAttributedString attributedStringWithAttachment:textAtt];
                //替换原文本
                [strM replaceCharactersInRange:rang withAttributedString:textAttStr];
            }
        }
    }
    //设置字体
    [strM addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, strM.length)];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;// 字体的行间距
    [strM addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, strM.length)];
    return strM;
}

///带附件textView的高度
+ (CGFloat)textViewHeightWith:(NSAttributedString *)attriStr textViewWith:(CGFloat)width withFont:(UIFont *)font textColor:(UIColor *)color
{
    NSMutableAttributedString *mutableAttri = [[NSMutableAttributedString alloc] initWithAttributedString:attriStr];
    [mutableAttri addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, mutableAttri.length)];
    [mutableAttri addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, mutableAttri.length)];
    CGSize size =  [mutableAttri boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil].size;
    return size.height;
}

///重新排列表情，最后一个加上删除按钮，不足补空
+ (NSArray *)emoticonsWith:(NSArray *)emoticonsArray
{
    NSMutableArray *tempArrayM = [NSMutableArray array];
    //加入删除按钮
    NSInteger index = 0;
    for (CYEmoticon *myemoticon in emoticonsArray) {
        [tempArrayM addObject:myemoticon];
        index ++;
        //第21位补删除按钮
        if (index%20 == 0) {
            CYEmoticon *emoticon = [[CYEmoticon alloc] init];
            emoticon.isDelete = YES;
            //加入数组中
            [tempArrayM addObject:emoticon];
        }
    }
    
    //当最后一页不足20个时候，用空按钮补齐
    if (emoticonsArray.count%20 == 0) {
        //正好排满
        return tempArrayM;
    }
    for (int i = 0; i < 20-emoticonsArray.count%20; i++) {
        CYEmoticon *emoticon = [[CYEmoticon alloc] init];
        emoticon.isEmpty = YES;
        [tempArrayM addObject:emoticon];
    }
    return tempArrayM;
}

@end
